#!/bin/bash
#Java home 设置
export JAVA_HOME="/usr/java/jdk1.7.0_79"
#JVM 参数设置
export JAVA_OPT="-Xms128M -Xmx256M"
#Jar 名称设置
MY_JAR_NAME="logserver.jar"
#应用名称设置
MY_APP_NAME="logserver"

#jre环境变量设置
export PATH=$PATH:"$JAVA_HOME/bin":"$JAVA_HOME/jre/bin"
export CLASSPATH=$CLASSPATH:"$JAVA_HOME/lib":"$JAVA_HOME/jre/lib":.

#查找 start所在的绝对目录
PRG="$0"
while [ -h "$PRG" ] ; do
  ls=`ls -ld "$PRG"`
  link=`expr "$ls" : '.*-> \(.*\)$'`
  if expr "$link" : '/.*' > /dev/null; then
    PRG="$link"
  else
    PRG=`dirname "$PRG"`/"$link"
  fi
done
PRGDIR=`dirname "$PRG"`
ABSOLUTE_DIR=`cd "$PRGDIR/" ; pwd`

#确定日志文件目录和文件
LOG_PREFIX=$ABSOLUTE_DIR/logs
if [ ! -d $LOG_PREFIX ]
then
   mkdir -p $LOG_PREFIX
fi
LOG="$LOG_PREFIX/run-log-`date +%F`.log"

PID_TEMP_FILE="/tmp/pid-`date +%s_%N`"
ps ax --width=2000 | grep "$ABSOLUTE_DIR"|grep "$MY_JAR_NAME"|grep "$MY_APP_NAME" |grep -v 'grep'| awk '{printf $1 " "}' > "$PID_TEMP_FILE"
read line < "$PID_TEMP_FILE"
rm -f "$PID_TEMP_FILE"
if [ -z "$line" ];
then
   echo "###Starting $MY_APP_NAME @ `date +%F_%H_%M_%S`">>"$LOG"
   RESULT=`cd $ABSOLUTE_DIR;java $JAVA_OPT -DWORK_TOP_PATH="$ABSOLUTE_DIR" -DMY_APPNAME="$MY_APP_NAME" -jar ${MY_JAR_NAME} >>"$LOG" 2>&1 &`
   RETCODE=$?
   echo "$MY_APP_NAME started with exit code=$RETCODE"
   exit $RETCODE
else
   echo "$MY_APP_NAME is alive with pid=${line},stop it first please."
   exit 1
fi


